package com.xydtech.ecard.merchant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.merchant.domain.EcardMerchantInfo;
import com.xydtech.ecard.merchant.domain.EcardMerchantPartInfo;
import com.xydtech.ecard.merchant.domain.EcardReleaseRecord;
import com.xydtech.ecard.merchant.service.IEcardMerchantInfoService;
import com.xydtech.ecard.merchant.service.IEcardMerchantPartInfoService;
import com.xydtech.ecard.merchant.service.IEcardMerchantVisitInfoService;
import com.xydtech.ecard.merchant.service.IEcardReleaseRecordService;
import com.xydtech.ecard.merchant.utils.MyExcelUtils;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片商户信息Controller
 *
 * @author xydtech
 * @date 2023-07-31
 */
@Controller
@RequestMapping("/merchant/info")
public class EcardMerchantInfoController extends BaseController
{
    private String prefix = "merchant";

    @Autowired
    private IEcardMerchantInfoService ecardMerchantInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEcardMerchantVisitInfoService ecardMerchantVisitInfoService;
    @Autowired
    private IEcardMerchantPartInfoService ecardMerchantPartInfoService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IEcardReleaseRecordService ecardReleaseRecordService;

    @RequiresPermissions("merchant:info:view")
    @GetMapping()
    public String merchant()
    {
        return prefix + "/merchant";
    }

    //跳转商户天眼查更多信息
    @RequiresPermissions("merchant:info:view")
    @GetMapping("/merchantTyc/{id}")
    public String moreInfo(@PathVariable("id") String id, ModelMap mmap)
    {
        String salt = getSalt();//盐值
        EcardMerchantInfo ecardMerchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(Long.valueOf(id), salt);
        mmap.put("ecardMerchantInfo", ecardMerchantInfo);
        return prefix + "/merchantTyc";
    }

    /**
     * 查询电子名片商户信息列表
     */
    @RequiresPermissions("merchant:info:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EcardMerchantInfo ecardMerchantInfo)
    {
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ShiroUtils.getSysUser().getDeptId());
        ecardMerchantInfo.setDictDeptId(sysDept.getDeptId());
        startPage();
        List<EcardMerchantInfo> list = ecardMerchantInfoService.selectEcardMerchantInfoList(ecardMerchantInfo);
        return getDataTable(list);
    }

    /**
     * 导出电子名片商户信息列表
     */
    @RequiresPermissions("merchant:info:export")
    @GetMapping("/export/{dataParam}")
    public void export(@PathVariable("dataParam") String dataParam, HttpServletResponse response)
    {
        String salt = getSalt();//盐值
        //处理查询条件
        EcardMerchantInfo ecardMerchantInfo = new EcardMerchantInfo();
        JSONArray parsed = (JSONArray) JSONObject.parse(dataParam);
        String ids = "";
        Map<String, Object> paramMap = new HashMap<>();
        for (Object o : parsed) {
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(o));
            if ("params[startDate]".equals(jsonObject.getString("name"))){
                paramMap.put("startDate",jsonObject.getString("value"));
            } else if ("params[endDate]".equals(jsonObject.getString("name"))){
                paramMap.put("endDate",jsonObject.getString("value"));
            } else if ("deptId".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setDeptId(jsonObject.getLong("value"));
            } else if ("id".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setId(jsonObject.getLong("value"));
            } else if ("userName".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setUserName(jsonObject.getString("value"));
            } else if ("handName".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setHandName(jsonObject.getString("value"));
            } else if ("industry".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setIndustry(jsonObject.getInteger("value"));
            } else if ("sortTime".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setSortTime(jsonObject.getString("value"));
            } else if ("releaseSts".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setReleaseSts(jsonObject.getString("value"));
            } else if ("visitSts".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setVisitSts(jsonObject.getString("value"));
            } else if ("tycsts".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setTycsts(jsonObject.getString("value"));
            } else if ("state".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setState(jsonObject.getInteger("value"));
            } else if ("ids".equals(jsonObject.getString("name"))){
                ids = jsonObject.getString("value");
            } else if ("id".equals(jsonObject.getString("name"))){
                ecardMerchantInfo.setId(jsonObject.getLong("value"));
            }
        }
        ecardMerchantInfo.setParams(paramMap);//时间条件
        List<EcardMerchantInfo> list = new ArrayList<>();
        if (ecardMerchantInfo.getDeptId() == null){
            ecardMerchantInfo.setDeptId(ShiroUtils.getSysUser().getDeptId());
        }
        //判断ids是否为空，不为空则导出选择的数据
        if (StringUtils.objIsNullOrEmpty(ids)){
            list = ecardMerchantInfoService.selectEcardMerchantInfoListByExport(ecardMerchantInfo, salt);
        } else {
            ids = ids.replaceAll("\\[","").replaceAll("]","");
            list = ecardMerchantInfoService.selectEcardMerchantInfoByIds(ids, salt);
        }

        for (EcardMerchantInfo merchantInfo : list) {
            //查询商户成员信息
            EcardMerchantPartInfo merchantPartInfo = new EcardMerchantPartInfo();
            merchantPartInfo.setMerchantId(merchantInfo.getId());
            merchantPartInfo.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            List<EcardMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoListByExport(merchantPartInfo, salt);
            merchantInfo.setMerchantPartDetail(partInfoList);
        }
        MyExcelUtils.exportExcel(list,
                "电子名片商户信息",
                "电子名片商户",
                EcardMerchantInfo.class,
                "电子名片商户信息文件" + System.currentTimeMillis() + ".xls", response);
    }

    /**
     * 新增电子名片商户信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存电子名片商户信息
     */
    @RequiresPermissions("merchant:info:add")
    @Log(title = "电子名片商户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(EcardMerchantInfo ecardMerchantInfo)
    {
        return toAjax(ecardMerchantInfoService.insertEcardMerchantInfo(ecardMerchantInfo));
    }

    /**
     * 修改电子名片商户信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        String salt = getSalt();//盐值
        EcardMerchantInfo ecardMerchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(id, salt);
        mmap.put("ecardMerchantInfo", ecardMerchantInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存电子名片商户信息
     */
    @RequiresPermissions("merchant:info:edit")
    @Log(title = "电子名片商户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(EcardMerchantInfo ecardMerchantInfo)
    {
        return toAjax(ecardMerchantInfoService.updateEcardMerchantInfo(ecardMerchantInfo));
    }

    /**
     * 删除电子名片商户信息
     */
    @RequiresPermissions("merchant:info:remove")
    @Log(title = "电子名片商户信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ecardMerchantInfoService.deleteEcardMerchantInfoByIds(ids));
    }


    /**
     * 选择转交的客户经理
     */
    @RequiresPermissions("merchant:info:handOver")
    @GetMapping("/handOver/{ids}")
    public String choiceUserByHand(@PathVariable("ids") String ids, ModelMap mmap) {
        mmap.put("ids", ids);
        mmap.put("merchantType", "2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        return prefix + "/choiceUser";
    }

    /**
     * 商户转交
     */
    @Log(title = "商户转交客户经理", businessType = BusinessType.UPDATE)
    @PostMapping("/allocation")
    @ResponseBody
    public AjaxResult allocation(Long registId,Long deptId, Long[] ids, Long userId) {
        /**查询机构*/
        //SysUser user = sysUserService.selectUserById(userId);
        if(registId == null){
            return AjaxResult.error("请选择移交人员！");
        }
        if(deptId == null){
            return AjaxResult.error("请选择移交的机构！");
        }

        //移交商户列表
        List<EcardMerchantInfo> ecardMerchantInfoList = new ArrayList<>();

        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardMerchantInfo ecardMerchantInfo = new EcardMerchantInfo();
            ecardMerchantInfo.setId(ids[i]);
            ecardMerchantInfo.setCreatorId(registId);
            ecardMerchantInfo.setDeptId(deptId);
            ecardMerchantInfoList.add(ecardMerchantInfo);
        }

        return toAjax(ecardMerchantInfoService.allocationEcardMerchantInfo(ecardMerchantInfoList,registId, userId));
    }

    /**
     * 释放商户
     * @param ids
     * @return: com.xydtech.common.core.domain.AjaxResult
     * @Author: lin
     * @Date: 2024/5/30 9:15
     */
    @RequiresPermissions("merchant:info:handOver")
    @Log(title = "释放商户", businessType = BusinessType.UPDATE)
    @PostMapping("/release")
    @ResponseBody
    public AjaxResult release(Long[] ids) {
        String salt = getSalt();//盐值
        //商户列表
        List<EcardMerchantInfo> ecardMerchantInfoList = new ArrayList<>();
        Long userId = ShiroUtils.getSysUser().getUserId();
        //新增商户释放记录
        List<EcardReleaseRecord> ecardReleaseRecordList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardMerchantInfo ecardMerchantInfo = new EcardMerchantInfo();
            ecardMerchantInfo.setId(ids[i]);
            ecardMerchantInfo.setCreatorId(null);
            ecardMerchantInfoList.add(ecardMerchantInfo);

            EcardMerchantInfo merchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(ids[i], salt);//查询商户信息
            //新增释放记录
            EcardReleaseRecord ecardReleaseRecord = new EcardReleaseRecord();
            ecardReleaseRecord.setReleaseId(userId);//释放人用户id
            ecardReleaseRecord.setMerchantId(ids[i]);//商户id
            ecardReleaseRecord.setBelongRegistId(merchantInfo.getCreatorId());//商户归属人注册id
            ecardReleaseRecord.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardReleaseRecordList.add(ecardReleaseRecord);
        }
        ecardReleaseRecordService.batchInsertEcardReleaseRecord(ecardReleaseRecordList);//批量新增释放记录
        int i = ecardMerchantInfoService.batchReleaseEcardMerchantInfo(ecardMerchantInfoList);
        return toAjax(i);
    }

    /**
     * 启用/停用商户
     *
     * @author yuzhiguo
     * @date 2024/7/12 下午5:25
     */
    @RequiresPermissions("merchant:info:switchOver")
    @Log(title = "启用/停用商户", businessType = BusinessType.UPDATE)
    @PostMapping("/switchOver")
    @ResponseBody
    public AjaxResult switchOver(Long[] ids, Integer state) {
        //商户列表
        List<EcardMerchantInfo> ecardMerchantInfoList = new ArrayList<>();

        for (int i = 0; i < ids.length; i++) {
            EcardMerchantInfo ecardMerchantInfo = new EcardMerchantInfo();
            ecardMerchantInfo.setId(ids[i]);
            ecardMerchantInfo.setState(state);
            ecardMerchantInfoList.add(ecardMerchantInfo);
        }
        int i = ecardMerchantInfoService.batchSwitchOverEcardMerchantInfo(ecardMerchantInfoList);
        return toAjax(i);
    }
}
